"""
监测结果页面接口
"""
import re

from app.libs.redprint import RedPrint
from app.db.models.jobs import Job
from app.db.models.tasks import Task
from flask import jsonify
from flask import g
from app.api.v2.common import query_page_data, param_input
from app.validators.result import History


api = RedPrint('result')


@api.route('/http-result', methods=['GET'])
def http_result():
    """http 结果列表"""
    q = {'uid': g.audit_uid}
    aggregate = [
        {'$match': q},
        {'$lookup': {'from': "tasks", 'localField': "httpResultId", 'foreignField': "_id", 'as': "httpResult"}},
        {'$sort': {'_id': -1}},
        {'$project': {'httpResult': 1, '_id': 1, 'enableMonitor': 1, 'httpSettings': 1, 'ignoredWarnIdMap': 1, 'target': 1}}
    ]
    jobs = list(Job.objects.aggregate(aggregate))
    return jsonify({'data': {'JobMany': jobs}})


@api.route('/ping-result', methods=['GET'])
def ping_result():
    """ping 结果列表"""

    q = {'uid': g.audit_uid}
    aggregate = [
        {'$match': q},
        {'$lookup': {'from': "tasks", 'localField': "pingResultId", 'foreignField': "_id", 'as': "pingResult"}},
        {'$sort': {'_id': -1}},
        {'$project': {'pingResult': 1, '_id': 1, 'enableMonitor': 1, 'pingSettings': 1, 'ignoredWarnIdMap': 1, 'target': 1}}
    ]
    jobs = list(Job.objects.aggregate(aggregate))
    return jsonify({'data': {'JobMany': jobs}})


@api.route('/history', methods=['GET'])
@param_input(History)
def history(query):
    q = {'uid': g.audit_uid, 'taskType': query['taskType']}
    if query.get('name'):
        q['name'] = query['name']
    if query.get('triggerType'):
        q['triggerType'] = query['triggerType']
    if query.get('targetSearch'):
        q['target'] = {'$regex': re.escape(query['targetSearch'])}
    if query.get('status'):
        q['status'] = query['status']
    if query.get('securityStatus'):
        q['$or'] = [{'securityStatus': status} for status in query['securityStatus']]

    endTime_q = []
    if query.get('endTime_gte'):
        endTime_q.append({'endTime': {'$gte': query['endTime_gte']}})
    if query.get('endTime_lt'):
        endTime_q.append({'endTime': {'$lt': query['endTime_lt']}})
    if endTime_q:
        q['$and'] = endTime_q

    if query.get('vulTriggerType'):
        ql = query['vulTriggerType'].split('-')
        if len(ql) == 1:
            sub_q = {'triggerType': query['vulTriggerType']}
        elif ql[1] == 'full':
            sub_q = {'triggerType': 'schedule', 'taskSettings.collect.type': 'full'}
        elif ql[1] == 'increment':
            sub_q = {'triggerType': 'scheduleIncrement'}
        else:
            sub_q = {}
        q.update(sub_q)

    page, count = query['page'], query['count']
    sort = [query['sort']]
    results, total = query_page_data(Task.objects, q, resp_fields=None, page=page, count=count, sort=sort)

    # 有些接口需要加上 job信息
    job_info = {job.pk: {'_id': job.pk, 'note': job.note}
                for job in Job.objects.filter(pk__in=[r['jobId'] for r in results])}
    for r in results:
        r['job'] = job_info.get(r['jobId'], {})
    return jsonify(data={'results': results, 'total': total})
